package com.base.controller.czb.czbapi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.base.controller.utils.CZB.CZBOilUtil;
import com.base.controller.utils.CZB.CZBTokenUtils;
import com.base.controller.utils.CZB.LocationUtils;
import com.base.po.czb_sdk.Gas;
import com.base.po.param.NetState;
import com.base.po.voip.Subscribers;
import com.base.po.voip.Users;
import com.base.service.CZB.GasService;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import com.base.utils.Produce;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/czbsearch")
public class CZB_SEARCH {
    @Autowired
    GasService gasService;
    @Autowired
    UsersService usersService;
    @Autowired
    SubscribersService subscribersService;

    @RequestMapping(value = "searchAllOil", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState searchOil(HttpServletRequest httpServletRequest,String parentId, String oilNum,Integer distance, Integer priority,
                       String longitude,  String latitude, String mobile, Integer page_size, Integer pageNo) {
        NetState netState = new NetState();
        if (page_size == null || page_size.equals(0)) {
            page_size = 10;
        }

        if (pageNo == null) {
            pageNo = 0;
        }

        if (mobile == null || mobile.equals("")) {
            netState.setData("手机信息为空");
            netState.setErrorCode(NetState.PARAMS_ERROR);
            return netState;
        }
        Boolean isMobile = Produce.isMobile(mobile);
        if (!isMobile) {
            netState.setData("手机号码验证不正确");
            netState.setErrorCode(NetState.PARAMS_ERROR);
            return netState;
        }
        if (longitude == null || latitude == null || longitude.equals("") || priority.equals("")) {
            netState.setData("经纬度信息必须上传");
            netState.setErrorCode(NetState.PARAMS_ERROR);
            return netState;
        }
        if (distance == null || distance.equals("")) {
            netState.setData("距离信息必须上传");
            netState.setErrorCode(NetState.PARAMS_ERROR);
            return netState;
        }
        if (oilNum == null || oilNum.equals("")) {
            netState.setData("油耗必须上传");
            netState.setErrorCode(NetState.PARAMS_ERROR);
            return netState;
        }

        if (parentId == null || parentId.equals("")) {
            netState.setData("代理商ID必须上传");
            netState.setErrorCode(NetState.PARAMS_ERROR);
            return netState;
        }
        String oilnum = CZBOilUtil.findOilNum(oilNum);
        if (oilnum == null) {
            netState.setData("油号信息不正确");
            netState.setErrorCode(NetState.PARAMS_ERROR);
            return netState;
        }
        Users users = usersService.selectByPrimaryKey(parentId);
        List<Subscribers> sub = subscribersService.selectBySub(mobile, parentId);
        if (sub.size() < 1 || users == null) {
            netState.setData("用户信息不正确");
            netState.setErrorCode(NetState.PARAMS_ERROR);
            return netState;
        }
        Double lat2 = Double.parseDouble(latitude);
        Double lon2 = Double.parseDouble(longitude);

        BigDecimal nowdistance = new BigDecimal(distance);

        List<Gas> gasList = gasService.selectAllJingWei();

        List<Map<String, Object>> listMaps1 = Lists.newArrayList();
        gasList.forEach(item -> {
            HashMap<String, Object> distanceResult = Maps.newLinkedHashMap();
            Double lon1 = item.getGasaddresslongitude().doubleValue();
            Double lat1 = item.getGasaddresslatitude().doubleValue();
            Double distance1 = LocationUtils.GetDistance(lat1, lon1, lat2, lon2);

            BigDecimal distance2 = new BigDecimal(distance1);
            if (nowdistance.compareTo(distance2) >= 0) {
                distanceResult.put("id", item.getGasid());
                distanceResult.put("distance", distance2);
                distanceResult.put("name", item.getGasname());
                listMaps1.add(distanceResult);
            }

        });
        JSONObject jsonObject = null;
        JSONArray result = null;
        Long Date = new Date().getTime();
        String tokenNow = CZBTokenUtils.createToken(Date, mobile);
        JSONObject jsons1 = JSONObject.parseObject(tokenNow);
        String code = jsons1.getString("code");
        if (!code.equals("200")) {
            tokenNow = "f8c7bcc13ed6469cba6c44e41f969376";
        } else {
            tokenNow = code;
        }
        //针对加油站返回数据超过100条处理：
        Integer numsSize=listMaps1.size();
        List<Map<String, Object>> listMaps = Lists.newArrayList();
        if (numsSize>=100){
            for (int i=0;i<99;i++){
                listMaps.add(listMaps1.get(i));
            }
        }else{
            for (int i=0;i<listMaps1.size();i++){
                listMaps.add(listMaps1.get(i));
            }
        }
        String gasIds = getGasIds(listMaps);
        String re = CZBTokenUtils.getGasDetails(Date, gasIds, mobile, tokenNow);
        jsonObject = JSONObject.parseObject(re);

      if (!jsonObject.getString("code").equals("200")){
          netState.setData("油站返回信息异常");
          netState.setErrorCode(NetState.SUCCESS_CONN);
          return netState;
      }
        JSONArray jsonArray = setDistance(jsonObject, listMaps, oilNum);
        List<JSONObject> list = JSONArray.parseArray(jsonArray.toJSONString(), JSONObject.class);
        Collections.sort(list, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                String a = o1.getString("distance");
                BigDecimal a1 = new BigDecimal(a);
                String b = o2.getString("distance");
                BigDecimal b1 = new BigDecimal(b);
                if (a1.compareTo(b1) > 0) {
                    return 1;
                } else if (a == b) {
                    return 0;
                } else
                    return -1;
            }
        });
        result = JSONArray.parseArray(list.toString());

        List<JSONObject> lista = Lists.newArrayList();
        if (priority.equals(2)) {  //2为按油价排序
            JSONArray ja = OrderByPrice(result, oilNum);
            JSONArray res = ja.getJSONArray(0);
            result = res;
        }

        //对返回的数据再处理一次
     for (int i=0;i<result.size();i++){
           Object items= result.get(i);
           JSONObject jsonObject1 = JSONObject.parseObject(items.toString());
           JSONArray jsonArray1=JSONArray.parseArray(jsonObject1.getString("oilPriceList"));
               for (Object js : jsonArray1) {
                   JSONObject json = JSONObject.parseObject(js.toString());
                   if (json.getString("oilName").equals(CZBOilUtil.findOilNum(oilNum))) {
                       jsonObject1.put("priceGunSearch",json.getString("priceGun"));
                       jsonObject1.put("priceOfficialSearch",json.getString("priceOfficial"));
                       jsonObject1.put("priceYfqSearch",json.getString("priceYfq"));
                       result.set(i,JSONObject.parse(jsonObject1.toString()));
                       break;
                   }

               }

        }
        netState.setData("参数调用成功");
        netState.setErrorCode(NetState.SUCCESS_CONN);
        netState.setJson(result);
        return netState;
    }


    private static String findDistance(List<Map<String, Object>> listMaps, String id) {
        for (Map<String, Object> a : listMaps) {
            if (a.get("id").equals("id")) {
                return a.get("distance").toString();
            }
        }
        return null;
    }

    /**
     * @Date: 2019/11/15 17:02
     * @Description: 生成ids
     */
    public static String getGasIds(List<Map<String, Object>> listMaps) {

        String gasIds = "";
        for (int i = 0; i < listMaps.size(); i++) {
            if (i != 0) {
                gasIds += "," + listMaps.get(i).get("id");
            } else {
                gasIds = listMaps.get(i).get("id").toString();
            }
        }
        return gasIds;
    }

    /**
     * @Date: 2019/11/15 17:18
     * @Description: 传入多个参数拼接
     */
    public JSONArray setDistance(JSONObject jsonObject, List<Map<String, Object>> listMaps, String oilNum) {
        GasService gasService = this.gasService;
        JSONArray jsonArray = jsonObject.getJSONArray("result");
        JSONArray resultJSON = new JSONArray();
       for(int i=0;i<jsonArray.size();i++){
           Object item=jsonArray.get(i);
            JSONObject jsonObject1 = JSONObject.parseObject(item.toString());
            Map<String, Object> params = JSONObject.parseObject(jsonObject1.toJSONString(), new TypeReference<Map<String, Object>>() {
            });
            String userName = jsonObject1.get("gasName").toString();
            Boolean flag = false; //是否应该传入参数
            JSONArray array = JSONArray.parseArray(params.get("oilPriceList").toString());
            for (Object js : array) {
                JSONObject json = JSONObject.parseObject(js.toString());
                if (json.getString("oilName").equals(CZBOilUtil.findOilNum(oilNum))) {
                    flag = true;
                }
            }
            for (Map<String, Object> s : listMaps) {
                if (s.get("name").equals(userName)) {
                    String dis = s.get("distance").toString();
                    String id = s.get("id").toString();
                    Gas gas = gasService.selectByPrimaryKey(id);
                    String addressdetail = gas.getGasaddress();
                    String gaslogosmall = gas.getGaslogosmall();
                    String gaslogobig = gas.getGaslogobig();
                    String address = gas.getProvincename() + " " + gas.getCityname() + " " + gas.getCountyname();
                    BigDecimal longitude = gas.getGasaddresslongitude();
                    BigDecimal latitude = gas.getGasaddresslatitude();
                    params.put("id", id);
                    params.put("longitude", longitude);
                    params.put("latitude", latitude);
                    params.put("gaslogosmall", gaslogosmall);
                    params.put("gaslogobig", gaslogobig);
                    params.put("address", address);
                    params.put("distance", dis);
                    if (flag) {
                        resultJSON.add(params);
                    }
                }

            }
        }
//        String json = JSONObject.toJSONString(result);

        return resultJSON;
    }

    /**
     * @Date: 2019/11/15 17:18
     * @Description: 传入参数，
     */
    private JSONArray OrderByPrice(JSONArray jsonArray, String oilNum) {

        JSONArray resultJSON = new JSONArray();
        //获取所有的数据
        Map<String, BigDecimal> re = Maps.newLinkedHashMap();
        for (Object jsonArray1 : jsonArray) {
            JSONObject js = JSONObject.parseObject(jsonArray1.toString());
            String gasId = js.getString("gasId");
            JSONArray jsonArray2 = JSONArray.parseArray(js.get("oilPriceList").toString());
            String price = null;
            for (Object o1 : jsonArray2) {
                JSONObject o2 = JSONObject.parseObject(o1.toString());
                if (o2.getString("oilName").equals(CZBOilUtil.findOilNum(oilNum))) {
                    price = o2.getString("priceYfq");
                    re.put(gasId, new BigDecimal(price));
                }
            }
        }

        List<Map.Entry<String, BigDecimal>> infoIds = new ArrayList<Map.Entry<String, BigDecimal>>(
                re.entrySet());

        // 排序
        Collections.sort(infoIds, new Comparator<Map.Entry<String, BigDecimal>>() {
            public int compare(Map.Entry<String, BigDecimal> o1,
                               Map.Entry<String, BigDecimal> o2) {
                return (o1.getValue().compareTo(o2.getValue()));
            }
        });

        List<Map<String, Object>> s1 = Lists.newArrayList();
        for (int i = 0; i < infoIds.size(); i++) {
            String id = infoIds.get(i).getKey();

            for (Object item : jsonArray) {
                JSONObject jsonObject1 = JSONObject.parseObject(item.toString());
                if (jsonObject1.getString("id").equals(id)) {
                    s1.add(jsonObject1.getInnerMap());
                }
            }
        }
        resultJSON.add(s1);

        return resultJSON;
    }


}
